package edu.gdpu.concurrent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * @author mazebin
 * @date 2021年 07月17日 17:39:13
 * 创建线程安全的集合
 * CopyAndWriteArrayList写较差，读较快
 * SynchronizedList写较快，读较差
 */
public class SynchronizedCollectionTest {
    public static void main(String[] args) {
       List<Object> objects = new ArrayList<>();
        List<Object> objects1 = Collections.synchronizedList(objects);
        objects1.add("a");
        objects1.add("b");
        objects1.add("c");
        new Thread(()->{

            try {
                Thread.sleep(3000);
                    Iterator<Object> iterator = objects1.iterator();
                    while (iterator.hasNext()){
                        System.out.println(iterator.next());
                    }


            } catch ( InterruptedException e ) {
                e.printStackTrace();
            }
        },"thread1").start();
        new Thread(()->{

                objects1.remove(2);

        },"thread2").start();
    }
}
